package com.geek.gkfood.framework.trace.model;

import com.geek.gkfood.framework.trace.util.TraceIdGeneratorUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * <h1>全局ID追踪对象。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2022-02-19
 *
 */
public class TraceInfo {

    public static final String TRACE_ID_NAME = "X-TraceId";
    public static final String SPAN_ID_NAME = "X-SpanId";
    public static final String APP_NAME = "X-AppName";

    private static String defaultAppName = getDefaultAppName();

    private String appName;
    private String traceId;
    private String spanId;
    private long createTime = System.currentTimeMillis();

    /** <h2>标记从哪里开始记录的</h2> **/
    private String marker;

    public TraceInfo(String traceId) {
        this(defaultAppName, traceId, null);
    }

    public TraceInfo(String appName, String traceId, String spanId) {
        this.appName = StringUtils.defaultString(appName, "-");
        this.traceId = TraceIdGeneratorUtils.getTraceId(traceId);
        this.spanId = TraceIdGeneratorUtils.getTraceId(spanId);
    }

    /**
     * <h2>创建空对象。</h2>
     *
     * @return
     */
    public static TraceInfo create() {
        return new TraceInfo(null);
    }

    /**
     * <h2>通过traceId创建对象。</h2>
     *
     * @param traceId
     * @return
     */
    public static TraceInfo create(String traceId) {
        return new TraceInfo(traceId);
    }

    public String getAppName() {
        return appName;
    }

    public String getTraceId() {
        return traceId;
    }

    public String getSpanId() {
        return spanId;
    }

    public String getMarker() {
        return marker;
    }

    public TraceInfo setMarker(String marker) {
        this.marker = marker;
        return this;
    }

    public long getCreateTime() {
        return createTime;
    }

    private static String getDefaultAppName() {
        return StringUtils.defaultString(System.getProperty("app.name"), "-");
    }

    public boolean isPassed() {
        return System.currentTimeMillis() - getCreateTime() >= 300000;
    }
}